﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using VehicleManagement.Models;
using VehicleManagement.Codes;
using VehicleManagement.ControllersServices;
using System.Collections;

namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "负责人,申请人")]
    public class ApplyController : Controller
    {
        ApplyServices applyServices = new ApplyServices();
        static bool stateChange = false;
        const int PAGE_MAX = 8;
        //
        // GET: /Apply/

        //[CustomerAuthorize(Roles = "负责人")]
        public ActionResult Index()
        {

            Hashtable ht = new Hashtable();
            SearchApplysByRequeast(ref ht);
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
                page = int.Parse(Request.Params["Page"]);

            return View(applyServices.SearchAllApplys(ht, (page - 1) * PAGE_MAX, PAGE_MAX));
            //return View(applyServices.GetAllApplys());
        }

        //
        // GET: /Apply/MyApplys

        /// <summary>
        /// 申请人查看自己的申请表
        /// </summary>
        /// <returns></returns>
        [CustomerAuthorize(Roles = "申请人")]
        public ActionResult MyApplys()
        {
            if (Session["UserID"] == null || Session["UserRole"] == null)
            {
                return View("../Home/Login");
            }
            else
            {
                Hashtable ht = new Hashtable();
                SearchMyApplysByRequeast(ref ht);

                return View(applyServices.GetApplysByApplicantID(ht));
            }
        }

        //
        // GET: /Apply/Details/2

        [CustomerAuthorize(Roles = "申请人")]
        public ActionResult Details(int id)
        {
            int applicantID = getApplicantIDByApplyID(id);

            if (Convert.ToInt32(Session["UserID"]) != applicantID)
            {
                return View("../Home/Login");
            }
            else
            {
                if (stateChange == true)
                {
                    ViewBag.StateErrorMessage = "您的申请已经通过，若要修改，请联系负责人!";
                    stateChange = false;
                }
                return View(applyServices.GetApplyByApplyID(id));
            }
        }

        //
        // GET: /Apply/Create

        [CustomerAuthorize(Roles = "申请人")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Apply/Create
        [HttpPost, CustomerAuthorize(Roles = "申请人")]
        public ActionResult Create(Apply apply)
        {
            if (Session["CompanyName"] == null || Session["UserID"] == null)
            {
                return View("../Home/Login");
            }

            apply.ApplicantID = Convert.ToInt32(Session["UserID"]);
            if (ModelState.IsValid)
            {
                apply.CompanyName = Session["CompanyName"].ToString();
                object obj = applyServices.CreateApply(apply);
                return RedirectToAction("MyApplys");
            }
            return View(apply);
        }

        //
        // GET: /Apply/Edit/5

        [CustomerAuthorize(Roles = "申请人")]
        public ActionResult Edit(int id)
        {
            int applicantID = getApplicantIDByApplyID(id);

            if (Convert.ToInt32(Session["UserID"]) != applicantID)
            {
                return View("../Home/Login");
            }
            else if (GetApplyState(id))
            {
                //Response.Write("<script language='javascript'>alert('您的申请已经通过，若要修改，请联系负责人!');</script>");
                Response.Redirect("../Details/" + id);
                stateChange = true;

                return View();
            }
            else
                return View(applyServices.GetApplyByApplyID(id));
        }

        //
        // POST: /Apply/Edit
        [HttpPost, CustomerAuthorize(Roles = "申请人")]
        public ActionResult Edit(Apply apply)
        {
            if (ModelState.IsValid)
            {
                int rows = applyServices.EditApply(apply);
                return RedirectToAction("MyApplys/" + apply.ApplicantID);
            }
            return View(apply);
        }

        //
        // GET: /Apply/DeleteApply/5

        //[CustomerAuthorize(Roles = "申请人")]
        //public ActionResult DeleteApply(int id)
        //{
        //    return View(applyServices.GetApplyByApplyID(id));
        //}

        //
        // POST:
        /// <summary>
        /// 使用AJAX删除一个申请，并且删除相关审批信息（不通过的才能删除）
        /// </summary>
        /// <param name="id">申请ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteApply"), CustomerAuthorize(Roles = "申请人")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (Request.IsAjaxRequest())
            {
                if (GetApplyState(id))
                    return Json(new { Result = "false", Message = "这条申请已经审批通过，不能删除" });
                else
                {
                    int i = applyServices.DeleteApply(id);
                    if (i > 0)
                    {
                        return Json(new { Result = "true", Message = "删除成功" });
                    }
                    else
                    {
                        return Json(new { Result = "false", Message = "删除失败" });
                    }
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "该方法只能通过AJAX方式调用" });
            }
        }

        /// <summary>
        /// 通过申请表ID获取申请人ID
        /// </summary>
        /// <param name="applyID">申请表ID</param>
        /// <returns>申请人ID</returns>
        [NonAction]
        private int getApplicantIDByApplyID(int applyID)
        {
            int applicantID = applyServices.getApplicantIDByApplyID(applyID);
            return applicantID;
        }

        /// <summary>
        /// 获取申请表状态 通过或不通过
        /// </summary>
        /// <param name="applyID">申请表ID</param>
        /// <returns>申请表状态 true or false</returns>
        [NonAction]
        private bool GetApplyState(int applyID)
        {
            ApprovalServices approvalServices = new ApprovalServices();
            bool applyState = false;
            applyState = approvalServices.GetApplyState(applyID);
            return applyState;
        }

        [NonAction]
        private void SearchApplysByRequeast(ref Hashtable ht)
        {
            string applicant = Request.Params["applicant"];
            string carType = Request.Params["carType"];
            string applyState = Request.Params["applyState"];
            string applicantForSearch = "%%";
            string carTypeForSearch = "%%";
            int applyStateForSearch = 3;

            if (applyState == "已审批")
                applyStateForSearch = 1;
            else if (applyState == "未审批")
                applyStateForSearch = 0;

            if (!string.IsNullOrEmpty(applicant) && applicant != "申请人")
                applicantForSearch = string.Format("%{0}%", applicant);
            if (!string.IsNullOrEmpty(carType) && carType != "车辆类型")
                carTypeForSearch = string.Format("%{0}%", carType);

            ht.Add("applicantForSearch", applicantForSearch);
            ht.Add("carTypeForSearch", carTypeForSearch);
            ht.Add("applyStateForSearch", applyStateForSearch);
            if (Session["CompanyName"] == null)
            {
                View("../Home/Login");
                return;
            }
            ht.Add("companyName", Session["CompanyName"].ToString());
            
        }

        [NonAction]
        private void SearchMyApplysByRequeast(ref Hashtable ht)
        {
            string carUse = Request.Params["carUse"];
            string carType = Request.Params["carType"];
            string applyState = Request.Params["applyState"];
            string carUseForSearch = "%%";
            string carTypeForSearch = "%%";
            int applyStateForSearch = 3;

            if (applyState == "已审批")
                applyStateForSearch = 1;
            else if (applyState == "未审批")
                applyStateForSearch = 0;

            if (!string.IsNullOrEmpty(carUse) && carUse != "申请用途")
                carUseForSearch = string.Format("%{0}%", carUse);
            if (!string.IsNullOrEmpty(carType) && carType != "车辆类型")
                carTypeForSearch = string.Format("%{0}%", carType);
            ht.Add("carUseForSearch", carUseForSearch);
            ht.Add("carTypeForSearch", carTypeForSearch);
            ht.Add("applyStateForSearch", applyStateForSearch);

            if (Session["CompanyName"] == null)
            {
                View("../Home/Login");
                return;
            }
            int id = Convert.ToInt32(Session["UserID"]);
            ht.Add("applicantID", id);
            ht.Add("companyName", Session["CompanyName"].ToString());
        }

        [ActionName("GetPagingInfo"),HttpGet]
        public ActionResult GetPagingInfo()
        {
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);

            Hashtable ht = new Hashtable();
            SearchApplysByRequeast(ref ht);
            int itemCount = applyServices.CountAllApplys(ht);
            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
